/*************************************************************************
 > File Name: monolith/interface/inference/face_rec_model.cc
 > Author: dzhang
 > Mail: dong.zhang@ingenic.com
 > Created Time : Sun 24 Jan 2021 09:19:07 PM CST
 > Description:
 ************************************************************************/

#include "monolith/interface/inference/face_rec_model.h"
#include "monolith/core/macros.h"
#include "monolith/interface/inference/utils.h"
#include "glog/logging.h"
CC_NAME_SPACE_BEGIN
namespace inference {

FaceRecModel* FaceRecModel::model_ = nullptr;
static FaceRecModel* FaceRecModel::get_instatnce(){
    CHECK(model_) << "Please init UltraFaceDectModel";
    return model_;
}

static int FaceRecModel::init(ModelParameter model_parameter){
    model_ = new FaceRecModel(model_parameter);
    return 0;
}

FaceRecModel::FaceRecModel(ModelParameter model_parameter) :
        Model(model_parameter) {

}

int FaceRecModel::run(uint8_t* data, std::vector<float> &face_feature,
        int input_width, int input_height, int input_channel) {
    CHECK(data) <<"FaceRecModel image is empty ,please check!";
    model_interpreter_->resizeTensor(input_tensor_, {1, 3, model_parameter_.input_height_, model_parameter_.input_width_});
    model_interpreter_->resizeSession(model_session_);
    std::shared_ptr<MNN::CV::ImageProcess> pretreat(
            MNN::CV::ImageProcess::create(MNN::CV::BGR, MNN::CV::RGB, model_parameter_.mean_.data(), 3,
                    model_parameter_.var_.data(), 3));
    pretreat->convert(data, model_parameter_.input_width_, model_parameter_.input_height_, model_parameter_.input_width_*model_parameter_.input_channel_, input_tensor_);
    model_interpreter_->runSession(model_session_);

    std::string feature = "fc1";
    MNN::Tensor *tensor_feature = model_interpreter_->getSessionOutput(model_session_, feature.c_str());
    MNN::Tensor tensor_feature_host(tensor_feature, tensor_feature->getDimensionType());
    tensor_feature->copyToHostTensor(&tensor_feature_host);
    auto shape = tensor_feature_host.shape();
    int batch_size = shape[0];
    int channel = shape[1];
    auto feature_data = tensor_feature->host<float>();
    face_feature.resize(channel);
    memcpy(face_feature.data(), feature_data, 128*4);
    ml::inference::l2normal(face_feature);
    return 0;

}

}
 // namespace inference
CC_NAME_SPACE_END
